//
//  PlayListViewController.m
//  Mecca
//
//  Created by Ryan Enguero on 6/10/14.
//  Copyright (c) 2014 TapDash Heuristics. All rights reserved.
//

#import "PlayListViewController.h"

#import "PlayListTableViewCell.h"

#import "AppDelegate.h"

#import "ParserClass.h"

#import "DownloadedSongs.h"

#import "Songs.h"

#import "UIManager.h"

#import "Album.h"

#import "LocalPlayerClass.h"

#import "UserDetails.h"

#import "PostClass.h"

#import "RotationTabViewController.h"

#import "PlaySongListViewController.h"

#import "JsonClass.h"

@interface PlayListViewController ()

@end

@implementation PlayListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
     [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchMusicDataFromCoreData];
//    UIImage *buttonImage = [UIImage imageNamed:@"userProfile.png"];
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//    [button setImage:buttonImage forState:UIControlStateNormal];
//    button.frame = CGRectMake(0, 100, buttonImage.size.width, buttonImage.size.height);
//    [button addTarget:self action:@selector(userProfile) forControlEvents:UIControlEventTouchUpInside];
//    
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"playlistNavImg.png"] forBarMetrics:UIBarMetricsDefault];
//    
//    UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
//    self.navigationItem.leftBarButtonItem = customBarItem;
//    
    [self.navigationController.navigationBar setHidden:YES];
    
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelTopsDL" object:@"cancelTopsDL"];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelEvents" object:@"cancelEvents"];
    [self.tableView setBackgroundColor:[UIColor colorWithRed:33/255.0 green:33/255.0 blue:33/255.0 alpha:1.0]];
    
    if ([[[ParserClass sharedItems] downloadedSongs] count] == 0) {
        UIAlertView *alertNoDownload = [[UIAlertView alloc]initWithTitle:@"" message:@"You dont have music on your playlist" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alertNoDownload show];
    }
    
//    UserDetails *userDetails = [[ParserClass sharedItems] userDetails][0];
//    
//    self.receivedData = [[NSMutableData alloc] init];
//    NSURLRequest *request = [[PostClass sharedItems] getPlaylist:[userDetails idUser]];
//    self.theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    
    
    
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [_receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error data = %@", error);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    
    if (connection == self.theConnection) {
        
        [_receivedData appendData:data];
        
        //  NSLog(@"data parse = %@", _receivedData);
        
    }
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    if (connection == self.theConnection) {
        //NSDictionary *dicdata = [NSJSONSerialization JSONObjectWithData:_receivedData options:kNilOptions error:nil];
        
        
        if (!(_receivedData == nil)) {
            
            NSLog(@"Count Confirmed");
            
            NSMutableDictionary *json = [JsonClass jsonParser:_receivedData];
            
            
            
            NSLog(@"playList = %@", json);
            
        }
        
        
        NSLog(@"Finish");
    }
    
}





-(void)userProfile{
    NSLog(@"User Profile");
    [[UIManager sharedItems]openLeft];
}

- (IBAction)userProfileAction:(id)sender{
    
    NSLog(@"User Profile");
    [[UIManager sharedItems]openLeft];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
   
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return  [[[ParserClass sharedItems] downloadedSongs] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Configure the cell...
    
    static NSString *cellIdentifier = @"Cell";
    
    PlayListTableViewCell *cell = (PlayListTableViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    
    
    
    
    if (cell == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PlayListTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    if( [indexPath row] % 2){
        [cell setBackgroundColor:[UIColor whiteColor]];
    }else{
        [cell setBackgroundColor:[UIColor colorWithRed:213/255.0 green:213/255.0 blue:213/255.0 alpha:1.0]];
    }
    
    DownloadedSongs *downloadedSongs = [[ParserClass sharedItems] downloadedSongs][indexPath.row];
    //Songs *songsD = [[ParserClass sharedItems] songDetails][indexPath.row];
    //Album *albumsD = [[ParserClass sharedItems] albumDetails][indexPath.row];
    //Album *album = [[ParserClass sharedItems] albumDetails][indexPath.row];
    
    cell.songNameLbl.text = [downloadedSongs songName];
    cell.lblDuration.text = [downloadedSongs durations];
    [cell setImageString:[NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@", [downloadedSongs songImg]]];
    cell.lblArtistName.text = [downloadedSongs artistname];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    
    NSLog(@"sadfjashfkjahfja %@", [downloadedSongs songImg]);
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    LocalPlayerClass *lp = [LocalPlayerClass sharedItems];
    
    [lp.audioPlayer stop];
    
    
//<<<<<<< .mine
////    DownloadedSongs *downloadedSongs = [[ParserClass sharedItems] downloadedSongs][indexPath.row];
////    
////    
////   // [self performSelectorOnMainThread:@selector(playAudioFromData:) withObject:[downloadedSongs songData] waitUntilDone:YES];
////    
////    [[LocalPlayerClass sharedItems] playAudioFromData:[downloadedSongs songData]];
////    
////  // [self playAudioFromData:[downloadedSongs songData]];
////    
////    
////    NSLog(@"id = %@", [downloadedSongs idSong]);
//=======
//  //  DownloadedSongs *downloadedSongs = [[ParserClass sharedItems] downloadedSongs][indexPath.row];
//>>>>>>> .r190
//    
//    
//    //  DownloadedSongs *downloadedSongs = [[ParserClass sharedItems] downloadedSongs][indexPath.row];
//    
//<<<<<<< .mine
//=======
//  //  [[LocalPlayerClass sharedItems] playAudioFromData:[downloadedSongs songData]];
//>>>>>>> .r190
//    
//    // [self performSelectorOnMainThread:@selector(playAudioFromData:) withObject:[downloadedSongs songData] waitUntilDone:YES];
//    
//<<<<<<< .mine
//    //  [[LocalPlayerClass sharedItems] playAudioFromData:[downloadedSongs songData]];
//=======
//    [UIManager sharedItems].playSongListView = [[PlaySongListViewController alloc] initWithNibName:@"PlaySongListViewController" bundle:nil];
//>>>>>>> .r190
//    
//<<<<<<< .mine
    // [self playAudioFromData:[downloadedSongs songData]];
    NSLog(@"Selected");
    
    self.playSongListView = [[PlaySongListViewController alloc] initWithNibName:@"PlaySongListViewController" bundle:nil];
    
    self.delegate = self.playSongListView;
    
    [self.delegate getPlaySongIndex:indexPath.row];
    
//    [[UIManager sharedItems].rotationView.navigationController pushViewController:self.playSongListView animated:YES];
//    [[UIManager sharedItems].rotationView presentViewController:self.playSongListView animated:YES completion:nil];
    [self.navigationController pushViewController:self.playSongListView animated:YES];
    
//  [self presentViewController:self.playSongListView animated:YES completion:nil];
    
    // NSLog(@"id = %@", [downloadedSongs idSong]);
//=======
//    self.delegate = [UIManager sharedItems].playSongListView;
//    
//    [self.delegate getPlaySongIndex:indexPath.row];
//    
//    [[UIManager sharedItems].rotationView.navigationController pushViewController:[UIManager sharedItems].playSongListView animated:YES];
//    
//    
//   // NSLog(@"id = %@", [downloadedSongs idSong]);
//>>>>>>> .r190

}


- (void) playAudioFromData: (NSData*) data {
    NSError *error = nil;
    
    //    player=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:NULL];
    //    player.delegate=self;
    //    [player play];
    self.audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];
    self.audioPlayer.delegate = self;
    [self.audioPlayer prepareToPlay];
    [self.audioPlayer play];
    
}





//- (void)viewDidUnload{
//    
//    //self.tableView = nil;
//    
//    [super viewDidUnload];
//    
//    [[ParserClass sharedItems] emptyDlSong];
//}

@end
